package face.pay.util;


import face.pay.entity.CpnWxAppInfo;
import lombok.extern.slf4j.Slf4j;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
@Slf4j
public class JSSDK_Config {

    public static Map<String, String> jsSDK_Sign(String url, CpnWxAppInfo cpnWxAppInfo) {
        Map<String, String> ret = new HashMap<String, String>();
        String nonce_str = create_nonce_str();
        String timestamp = create_timestamp();
        String jsapi_ticket = cpnWxAppInfo.getTicket();
        String str;
        String signature = "";

        str =   "jsapi_ticket=" + jsapi_ticket +
                "&noncestr=" + nonce_str +
                "&timestamp=" + timestamp +
                "&url=" + url;

        ret.put("url", url);
        ret.put("appId", cpnWxAppInfo.getAppId());
        ret.put("jsapi_ticket", jsapi_ticket);
        ret.put("nonceStr", nonce_str);
        ret.put("timestamp", timestamp);
        try {

             signature =SHA1(str);
        }  catch (Exception e) {
            e.printStackTrace();
        }

        ret.put("signature", signature);
        log.info(ret.toString());
        return ret;
    }

    public static String SHA1(String decript) {
        try {
            MessageDigest digest = java.security.MessageDigest.getInstance("SHA-1");
            digest.update(decript.getBytes());
            byte messageDigest[] = digest.digest();
            // Create Hex String
            StringBuffer hexString = new StringBuffer();
            // 字节数组转换为 十六进制 数
            for (int i = 0; i < messageDigest.length; i++) {
                String shaHex = Integer.toHexString(messageDigest[i] & 0xFF);
                if (shaHex.length() < 2) {
                    hexString.append(0);
                }
                hexString.append(shaHex);
            }
            return hexString.toString();

        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return "";
    }

    private static String create_nonce_str() {
        return UUID.randomUUID().toString();
    }

    private static String create_timestamp() {
        return Long.toString(System.currentTimeMillis() / 1000);
    }

    public static void main(String[] args) {
        CpnWxAppInfo cpnWxAppInfo =  new CpnWxAppInfo();

        cpnWxAppInfo.setTicket("LIKLckvwlJT9cWIhEQTwfDWa0LBQ_pzmc9c_cOiLQelDCHAt1lkCmCPNu5fRoTVHPl8uXuHIE0bCCUangaFNVA");

        String nonce_str = "b275e89a-f237-4fef-b1a8-1a80d05475c6";

        String url="http://www.baidu.com";

        String timestamp  = "1574938344";

        String str =   "jsapi_ticket=LIKLckvwlJT9cWIhEQTwfDWa0LBQ_pzmc9c_cOiLQelDCHAt1lkCmCPNu5fRoTVHPl8uXuHIE0bCCUangaFNVA" +
                "&noncestr=" + nonce_str +
                "&timestamp=" + timestamp +
                "&url=" + url;
       String  signature =SHA1(str);
        System.out.println(signature);
    }

}
